package service

import (
	"dsc-server/domain/dto"
	"dsc-server/pkg/model"
	"fmt"

	"gorm.io/gorm"
)

// GroupService 处理API分组相关的服务
type GroupService struct {
	DB *gorm.DB
}

// NewGroupService 创建GroupService实例
func NewGroupService(db *gorm.DB) *GroupService {
	return &GroupService{DB: db}
}

// Insert 添加API分组
func (s *GroupService) Insert(group *model.ApiGroup) dto.Result {
	if err := s.DB.Create(group).Error; err != nil {
		return dto.FailureMessage(nil, fmt.Sprintf("添加失败: %v", err))
	}

	return dto.SuccessMessage(nil, "添加成功")
}

// DeleteById 删除API分组
func (s *GroupService) DeleteById(id uint) dto.Result {
	// 检查分组下是否有API
	var count int64
	if err := s.DB.Model(&model.ApiConfig{}).Where("group_id = ? AND is_deleted = 0", id).Count(&count).Error; err != nil {
		return dto.FailureMessage(nil, fmt.Sprintf("检查分组使用情况失败: %v", err))
	}

	if count > 0 {
		return dto.FailureMessage(nil, "该分组下还有API，不可删除！")
	}

	// 开始事务
	tx := s.DB.Begin()

	// 删除分组
	if err := tx.Model(&model.ApiGroup{}).Where("id = ?", id).Update("is_deleted", 1).Error; err != nil {
		tx.Rollback()
		return dto.FailureMessage(nil, fmt.Sprintf("删除分组失败: %v", err))
	}

	// 删除分组相关的权限
	if err := tx.Model(&model.ApiAuth{}).Where("group_id = ?", id).Update("is_deleted", 1).Error; err != nil {
		tx.Rollback()
		return dto.FailureMessage(nil, fmt.Sprintf("删除分组权限失败: %v", err))
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return dto.FailureMessage(nil, fmt.Sprintf("提交事务失败: %v", err))
	}

	return dto.SuccessMessage(nil, "删除成功")
}

// GetAll 获取所有API分组
func (s *GroupService) GetAll() ([]*model.ApiGroup, error) {
	var groups []*model.ApiGroup
	result := s.DB.Where("is_deleted = 0").Find(&groups)
	return groups, result.Error
}
